/*
 * 处理手机端装修模块拖拽的js
 */

$(function() {
	/*
	 * 设置初始化变量
	 */
	var flag = true;
	var temp = '';
	var uid = '';

	if (typeof (topic_id) == 'undefined') {
		topic_id = 0;
	}
	if (typeof (goods_tpl_id) == 'undefined') {
		goods_tpl_id = 0;
	}
	if (typeof (comstore_group_id) == 'undefined') {
		comstore_group_id = 0;
	}
	/* -------------------- 主区域拖拽事件start ---------------------- */

	/**
	 * 放置事件
	 */
	$('.SZY-TEMPLATE-MAIN-CONTAINER').droppable({
		activeClass: "dragactive",
		hoverClass: "draghover",
		accept: ":not(.ui-sortable-helper)", // Reject clones generated by
		drop: function(e, ui) {
			if (flag == true) {
				$('.SZY-TEMPLATE-MAIN-CONTAINER').find('li.drag').addClass('hide');
				$.ajax({
					type: 'get',
					url: 'select-template',
					async: false,
					dataType: "json",
					data: {
						id: ui.draggable[0].id,
						code: ui.draggable['context']['dataset']['code'],
						sort: $(".drop-item").size() + 1,
						page: page,
						topic_id: topic_id,
						goods_tpl_id: goods_tpl_id,
						position: $(ui.draggable[0]).parents('.SZY-TEMPLATE-MAIN-CONTAINER').data('position'),
						comstore_group_id: comstore_group_id
					},
					beforeSend: function() {
						$.loading.start();
					},
					success: function(result) {
						temp = result.data;
						uid = result.uid;
						$.loading.stop();
						$.msg(result.message);
						flag = false;
					}
				});
			}
		}
	}).sortable({
		items: '.drop-item',
		scroll: true,
		tolerance: 'intersect',
		opacity: 0.6,
		distance: 50,
		placeholder: 'position-box',
		sort: function() {
			// 获取由 droppable 与 sortable 交互而加入的条目
			// 使用 connectWithSortable 可以解决这个问题，但不允许您自定义 active/hoverClass 选项
			$(this).removeClass("active");
		},
		stop: function(event, ui) {
			flag = true;
			if (ui.item[0].id == '') {
				if (temp) {
					var $el = $(temp);
					var i = $(this).find('li.drag').prevAll('div.drop-item').size() - 1;
					if ($(this).find('.drop-item').size() > 0) {
						if (i < 0) {
							$(this).find('.drop-item').eq(0).before($el);
						} else {
							$(this).find('.drop-item').eq(i).after($el);
						}
					} else {
						$(this).append($el);
					}

					refreshTpl(page, uid);
				}
				$(this).find('li.drag').remove();
			}
			savesort(page, ui.item.attr('id'));
		}
	});

	$('.drag').draggable({
		appendTo: 'body',
		connectToSortable: ".SZY-TEMPLATE-MAIN-CONTAINER",
		helper: 'clone',
		cursor: 'move',
		revert: 'invalid',
		opacity: 0.6,
		zIndex: 99
	});

	$(".SZY-TEMPLATE-MAIN-CONTAINER").disableSelection();

	/* -------------------- 主区域拖拽事件end ---------------------- */

	/* -------------------- 公共方法 ------------------------ */

	/**
	 * 页面发布
	 */
	$('.SZY-TPL-RELEASE').click(function() {
		var target = $(this);
		$.loading.start();
		$.ajax({
			type: 'get',
			// async: false, // 同步请求
			url: 'setting',
			dataType: 'json',
			data: {
				page: page,
				topic_id: topic_id,
                		comstore_group_id: comstore_group_id
			},
			success: function(result) {
				if (result.code == 0 && result.url != null) {
					if ($.modal(target)) {
						$.modal(target).show();
					} else {
						var modal = $.modal({
							title: "提示",
							trigger: target,
							content: "<div class='success-box'><h1 class='success-title'>发布成功</h1><div class='success-description'>页面链接为： " + result.url + "</div><div class='success-box-bootom'><div class='pic-wrapper'><img src='" + result.qrcode + "'></div><div class='pic-info'>用手机扫描左侧二维码，查看装修效果</div></div></div>"
						});
					}

				} else {
					$.msg(result.message);
				}
			}
		}).always(function() {
			$.loading.stop();
		});
	});

	/**
	 * 预览
	 */
	$('.SZY-TPL-PREVIEW').click(function() {
		var target = $(this);
		$.loading.start();
		$.ajax({
			type: 'get',
			// async: false, // 同步请求
			url: 'preview',
			dataType: 'json',
			data: {
				page: page,
				topic_id: topic_id,
				is_preview: 1,
				comstore_group_id: comstore_group_id
			},
			success: function(result) {
				if (result.code == 0) {
					if (result.qrcode) {
						$.loading.start();
						$.open({
							title: '扫码预览',
							btn: false,
							content: '<div class="success-box"><img src="' + result.qrcode + '"></div>'
						});
					} else {
						window.open(result.url);
					}
				} else {
					$.msg(result.message);
				}
			}
		}).always(function() {
			$.loading.stop();
		});
	});

	/**
	 * 整站改色模块
	 */
	$('.SZY-SITE-STYLE').click(function() {
		$.loading.start();
		var group = $(this).data('group');
		modal = $.modal($(this));
		if (modal) {
			modal.show();
			$.loading.stop();
		} else {
			modal = $.modal({
				title: '自定义风格',
				trigger: $(this),
				ajax: {
					url: '/system/config/index?group=' + group,
				},

			});
		}
	});

	/**
	 * 整站改色模块
	 */
	$('.SZY-SHOP-STYLE').click(function() {
		var group = $(this).data('group');
		$.loading.start();
		modal = $.modal($(this));
		if (modal) {
			modal.show();
			$.loading.stop();
		} else {
			modal = $.modal({
				title: '自定义风格',
				trigger: $(this),
				ajax: {
					url: '/shop/config/index?group=' + group,
				},

			});
		}
	});

	/**
	 * 模板备份
	 */
	$('.SZY-TPL-BACKUP').click(function() {
		$.loading.start();
		modal = $.modal($(this));
		if (modal) {
			modal.show();
			$.loading.stop();
		} else {
			modal = $.modal({
				title: '模板备份',
				trigger: $(this),
				ajax: {
					url: '/site/tpl-backup?design_page=' + page,
					data: {
						action: 'add',
						output: 1,
						comstore_group_id: comstore_group_id
					}
				},

			});
		}
	});

	/**
	 * 使用备份
	 */
	$('.SZY-TPL-USE').click(function() {
		$.loading.start();
		modal = $.modal($(this));
		if (modal) {
			modal.show();
			$.loading.stop();
		} else {
			modal = $.modal({
				title: '使用备份',
				trigger: $(this),
				ajax: {
					url: '/site/tpl-backup.html',
					data: {
						action: 'list',
						output: 1,
						design_page: page,
						search_id: $(this).data('id'),
						comstore_group_id: comstore_group_id
					}
				},

			});
		}
	});

	// 全选处理
	$('.all-checkbox').change(function() {
		if ($(this).is(":checked")) {
			$('#mobile_helper tbody .table-list-checkbox').prop("checked", true);
		} else {
			$('#mobile_helper tbody .table-list-checkbox').prop("checked", false);
		}
	});

	$('#mobile_helper tbody').on('change', '.table-list-checkbox', function() {
		if ($('#mobile_helper tbody .table-list-checkbox:checked').length == $('#mobile_helper tbody .table-list-checkbox').length) {
			$('.all-checkbox').prop("checked", true);
		} else {
			$('.all-checkbox').prop("checked", false);
		}
	});

	// 批量删除
	$('.batch-delete').click(function() {
		var uids = [];
		$.each($('#mobile_helper tbody .table-list-checkbox'), function() {
			if ($(this).is(":checked")) {
				uids.push($(this).val());
			}
		});
		if (uids.length == 0) {
			$.msg('您没有选择任何待处理的数据！');
			return;
		}
		$.confirm("您确定批量删除吗？", function() {
			$.post('/design/tpl-setting/batch-delete', {
				uids: uids
			}, function(result) {
				if (result.code == 0) {
					$.each(result.data, function(i, uid) {
						$('#' + uid).detach();
					});
					savesort(page, '');
				}
				$.msg(result.message);
			}, 'JSON');
		});
	});

	// 批量设置
	$('.batch-valid').click(function() {
		var uids = [];
		$.each($('#mobile_helper tbody .table-list-checkbox'), function() {
			if ($(this).is(":checked")) {
				uids.push($(this).val());
			}
		});
		if (uids.length == 0) {
			$.msg('您没有选择任何待处理的数据！');
			return;
		}
		var is_valid = $(this).data('value');
		$.confirm("您确定批量设置吗？", function() {
			$.post('/design/tpl-setting/batch-valid-tpls', {
				uids: uids,
				is_valid: is_valid
			}, function(result) {
				if (result.code == 0) {
					refreshTpl(page, '');

					$.each(result.data, function(i, uid) {
						$('#mobile_helper tbody tr[data-id="' + uid + '"]').find('.table-list-checkbox').prop("checked", true);
					});
				}

				$.msg(result.message);
			}, 'JSON');
		});
	});
});

$('.SZY-TEMPLATE-MAIN-CONTAINER').on('mouseover', '.drop-item', function() {
	$('.SZY-TEMPLATE-MAIN-CONTAINER').find('.drop-item').removeClass('current');
	$(this).addClass('current');
	$("#mobile_helper").find('.columnNameText').removeClass('selected');
	$("#mobile_helper").find("#columnNameText_" + $(this).attr('id')).addClass('selected');
});

$('.SZY-TEMPLATE-MAIN-CONTAINER').on('mouseout', '.drop-item', function() {
	$(this).removeClass('current');
	$("#mobile_helper").find('.columnNameText').removeClass('selected');
});
function savesort(page, uid) {
	var arr = [];
	$.each($(".drop-item"), function(i, v) {
		var tpl = {};
		tpl.uid = $(v).attr('id');
		tpl.sort = i + 1;
		if (tpl.uid && tpl.sort) {
			arr.push(tpl);
		}
	});
	if (arr.length > 0) {
		$.ajax({
			type: 'post',
			url: 'sort',
			data: {
				tpl: arr,
			},
			success: function(result) {
				// 调用模板设置助手
				getHelper(uid);
			}
		});
	} else {
		getHelper(uid);
	}
}

function savesortHelper() {
	var arr = [];
	$.each($("#mobile_helper").find('tbody tr'), function(i, v) {
		var tpl = {};
		tpl.uid = $(v).data('id');
		tpl.sort = i + 1;
		tpl.position = $(v).data('position');
		if (tpl.uid && tpl.sort) {
			arr.push(tpl);
		}
	});
	$.ajax({
		type: 'post',
		url: 'sort',
		data: {
			tpl: arr,
		},
		success: function(result) {
			var item = $('<div></div>');
			$.each(arr, function(i, v) {
				item.append($('.SZY-TEMPLATE-MAIN-CONTAINER').find("#" + v.uid));
			});
			$('.SZY-TEMPLATE-MAIN-CONTAINER').html(item);
		}
	});
}

function clearTplData() {
	chk_value = [];
	data = [];
	data_m = {};
}

function delTpls(uid) {
	$.confirm("您确定要删除这个模块吗?", function(s) {
		if (s) {
			$.ajax({
				type: 'get',
				url: 'delete-tpls',
				dataType: 'json',
				data: {
					uid: uid,
				},
				beforeSend: function() {
					$.loading.start();
				},
				success: function(result) {
					$('#' + uid).detach();
					// 从新排序
					$.loading.stop();
					savesort(page, uid);
					$.msg(result.message);
				}
			});
		}
	});
}

function open_selector(uid, type, cat_id, max) {
	$.selector({
		uid: uid,
		type: type,
		cat_id: cat_id,
		max: max,
	});
}

// 设置是否有效
function setIsValidTpls(uid) {
	$.loading.start();
	$.get('valid-tpls', {
		uid: uid
	}, function(result) {
		if (result.code == 0) {
			refreshTpl(result.data.page, result.data.uid);
		}
		$.msg(result.message);
		$.loading.stop();
	}, 'JSON');
}

// 上下交换位置
function setSortTpls(uid, move) {
	var tpl = $("#" + uid);
	if (move == 'up') {
		var tplprevs = tpl.prevAll(".drop-item");
		var tplprev = tplprevs[0];
		if (tplprev) {
			tpl.insertBefore($("#" + tplprev.id));
			// $('.special-item').mCustomScrollbar('scrollTo',
			// tpl.position().top);
		} else {
			$.msg("已经到顶了!");
		}
	}
	if (move == 'down') {
		var tplnexts = tpl.nextAll(".drop-item");
		var tplnext = tplnexts[0];
		if (tplnext) {
			$("#" + tplnext.id).insertBefore(tpl);
			// $('.special-item').mCustomScrollbar('scrollTo',
			// tpl.position().top);
		} else {
			$.msg("已经到底了!");
		}
	}
	savesort(page, uid);
}

/*
 * 模板设置助手js
 */
function getHelper(id) {

	/* 模板设置助手js */

	// 生成页面导航助手
	$("#mobile_helper").find("tbody").html("");
	var count = 0;
	$(".drop-item").each(function(i, v) {
		var cardinal = ''
		if (i % 2 == 1)
			cardinal = "class='cardinal'";
		var title = $(this).data("tpl_name");
		var uid = $(this).attr('id');
		var selected_class = '';
		var tpl_type = $(this).data("tpl_type");
		var position = $(this).parents('.SZY-TEMPLATE-MAIN-CONTAINER').data('position');
		var is_valid_item = '';
		var is_valid_class = '';
		if ($(this).data('is_valid') > 0) {
			is_valid_item = "<i class='fa fa-check-circle'></i>显示";
			is_valid_class = 'open';
		} else {
			is_valid_item = "<i class='fa fa-times-circle-o'></i>隐藏";
			is_valid_class = 'no-open';
		}
		var element = $($.parseHTML("<tr " + cardinal + " data-id='" + uid + "' data-position='" + position + "'><td><input class='checkBox table-list-checkbox' value='" + uid + "' type='checkbox'><span class='columnParent'>" + tpl_type + "</span><span class='columnNameText' id='columnNameText_" + uid + "'>" + title + "</span></td>" + "<td><span class='ico-switch " + is_valid_class + "' onclick=setIsValidTpls('" + uid + "')> " + is_valid_item + "</span></td>" + "<td class='handle'><a href=javascript:delTpls('" + uid + "') title='删除'><i class='fa fa-trash-o'></i></a></a></a><a class='handle' href=javascript:setSortTpls('" + uid + "','up') title='上移'><i class='fa fa-arrow-circle-o-up'></i></a><a class='handle' href=javascript:setSortTpls('" + uid + "','down') title='下移'><i class='fa fa-arrow-circle-o-down'></i></a></td></tr>"));
		if (id != '' && id == uid) {
			$(element).find('.columnNameText').addClass('selected');
		}
		$("#mobile_helper").find("tbody").append(element);

		var target = this;
		$(element).click(function() {
			var position = 0;
			$(this).find('.columnNameText').addClass('selected');
			$('.SZY-TEMPLATE-MAIN-CONTAINER').find('.drop-item').removeClass('current');
			$('.SZY-TEMPLATE-MAIN-CONTAINER').find("#" + uid).addClass('current');
			$(this).siblings().find('.columnNameText').removeClass('selected');
			var top = $('#' + uid).position().top - 150;
			if (top < 0) {
				top = 0;
			}
			$('html, body').animate({
				scrollTop: top
			}, 500);
			// $('.special-item').mCustomScrollbar('scrollTo', top);

		});
		count++;
	});

	if (page != 'm_goods') {
		$("#mobile_helper").find('tbody').sortable({
			revert: true,
			tolerance: 'intersect',
			opacity: 0.6,
			out: function(event, ui) {
				savesortHelper();
			}
		});
	}

	// $("#helper_tool_nav").find(".count").html(count);
}

var _timer = {};
function delay_till_last(id, fn, wait) {

	if (_timer[id]) {
		window.clearTimeout(_timer[id]);
		delete _timer[id];
	}

	return _timer[id] = window.setTimeout(function() {
		fn();
		delete _timer[id];
	}, wait);
}

// 刷新当前模板
function refreshTpl(page, uid) {
	clearTplData();
	$.ajax({
		type: 'get',
		async: false, // 同步请求
		url: "tpl-ref",
		dataType: 'json',
		data: {
			page: page,
			uid: uid,
			topic_id: topic_id,
			goods_tpl_id: goods_tpl_id
		},
		beforeSend: function() {
			// $.loading.start();
		},
		success: function(tpls) {
			$.each(tpls, function(index, value) {
				var $el = $(value.file);
				var is_valid_class = '';
				var is_eye_valid_class = '';

				if (value.is_valid > 0) {
					is_valid_class = 'fa fa-check-circle-o';
					is_eye_valid_class = 'hide-btn';
				} else {
					is_valid_class = 'fa fa-times-circle-o';
					is_eye_valid_class = 'show-btn';
				}
		
				$el.append($('<div class="item_type">' + value.tpl_name + '</div>'));
				var $handle = $('<div class="operateEdit"></div>');

				$handle.append($('<a class="decor-btn upMove-btn"><div class="selector-box"><div class="arrow"></div><i class="fa fa-arrow-circle-o-up"></i>上移</div></a>').click(function() {
					setSortTpls(value.uid, 'up');
				}));
				$handle.append($('<a class="decor-btn downMove-btn"><div class="selector-box"><div class="arrow"></div><i class="fa fa-arrow-circle-o-down"></i>下移</div></a>').click(function() {
					setSortTpls(value.uid, 'down');
				}));

				$handle.append($('<a class="decor-btn ' + is_eye_valid_class + '"><div class="selector-box"><div class="arrow"></div><i class="' + is_valid_class + '"></i>' + value.format_is_valid + '</div></a>').click(function() {
					setIsValidTpls(value.uid);
				}));
				$handle.append($('<a class="decor-btn deletes-btn"><div class="selector-box"><div class="arrow"></div><i class="fa fa-trash-o"></i>删除</div></a>').click(function() {
					delTpls(value.uid);
				}));
				$el.append($handle);
				
				$('.SZY-TEMPLATE-MAIN-CONTAINER').find("#" + value.uid).replaceWith($el);
			});
			// 图片缓载
			$.imgloading.loading();
			// 生成模板助手
			getHelper(uid);
		}
	});
}

// 刷新头部
function ajaxRender(page, tpl, container) {
	if (tpl == undefined || tpl == '') {
		$.go(window.location);
		return;
	}
	if (topic_id > 0) {
		page = page + topic_id;
	}
	var data = {};
	data.page = page;
	data.tpl = tpl;
	if (topic_id > 0) {
		data.topic_id = topic_id;
	}
	$.ajax({
		type: 'get',
		url: "ajax-render",
		dataType: 'json',
		data: data,
		success: function(result) {
			if (result.code == 0) {
				$(container).html($.parseHTML(result.data));
			}

		}
	});
}
// 公告版式一
function comments_scroll(id) {
	var liLen = $(id).find('.hot ul li').length;
	var num3 = 0;
	$(id + ' .hot').find('ul').append($(id + ' .hot ul').html());
	function autoplay() {
		if (num3 > liLen) {
			num3 = 1;
			$(id + ' .hot').find('ul').css('top', 0);
		}
		$(id + ' .hot').find('ul').stop().animate({
			'top': -60 * num3
		}, 500);
		num3++;
	}
	var mytime = setInterval(autoplay, 5000);
}

// 公告版式二
function notice_scroll(id) {
	var totalHeight = $(id + ' .shop-notice-info').height();
	var top = 0;
	var lineHeight = 30;
	var mytime;
	$(id + ' .shop-notice-info p').eq(0).clone().appendTo('.shop-notice-info');
	function marquee() {
		if (top >= totalHeight + lineHeight) {
			top = 0;
			$(id + ' .shop-notice-info').css('top', 0);
		}
		$(id + ' .shop-notice-info').stop().animate({
			'top': -top
		}, 600);
		top = top + lineHeight;
	}
	mytime = setInterval(marquee, 3000);
}